#include "misc.hpp"
#include "mallocSharedPtr.hpp"

#include "mandarava/linux/tcpConnection.hpp"
using namespace wheels;

tcpConnection :: tcpConnection( int fd , sockaddr_in * addr , size_t addrLen , tcpServer * svr ):
	m_fd__( fd ),
	p_svr__( svr )
{
	memcpy( &peerAddr__ , addr , addrLen );
}

tcpConnection :: ~tcpConnection()
{
	::close( m_fd__.load();
}

void tcpConnection :: onReadyRead( const uint8_t* data , size_t len )
{
	UNUSED( data );
	UNUSED( len );
	mallocSharedPtr< char >   buff( 1096 );
	size_t len = ::read( m_fd__.load() , buff.get() , 1096 );
	buff.dataLen( len );
	mandaravaCommand * cmd = mandaravaCommand::get();
	if( cmd ){ return; }

	mandaravaEvt evt = { mandaravaEvtID::EVT_DATA , this , buff_t( 0 ) };

	cmd->send( evt , buff );
}

void tcpConnection :: close()
{
	::close( m_fd__.load() );
}

void tcpConnection :: send( const char * data , size_t len )
{
	size_t len = ::write( m_fd__.load() , data , len );
	if( len < 0 ){
		const char * err = strerror( errno );
		mandaravaCommand * cmd = mandaravaCommand::get();
		if( cmd ){ return; }
		std::string emsg( err );
		mandaravaEvt evt = { mandaravaEvtID::EVT_ERROR , this , buff_t( 0 ) };

		cmd->send( evt , emsg );
	} 
}
	
void tcpConnection :: send( wheels::mallocSharedPtr< char >& data )
{
	size_t len = ::write( m_fd__.load() , data.get() , data.dataLen() );

	if( len < 0 ){
		const char * err = strerror( errno );
		mandaravaCommand * cmd = mandaravaCommand::get();
		if( cmd ){ return; }
		std::string emsg( err );
		mandaravaEvt evt = { mandaravaEvtID::EVT_ERROR , this , buff_t( 0 ) };

		cmd->send( evt , emsg );
	} 
}
